package com.usian.skill.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.skill.pojo.OrderInfo;
import com.usian.skill.pojo.SkillOrder;
import com.usian.skill.service.GoodsService;
import com.usian.skill.service.SkillGoodsService;
import com.usian.skill.service.SkillOrderService;
import com.usian.skill.service.SkillService;
import com.usian.skill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/skill")
public class SkillController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private SkillOrderService skillOrderService;

    @Autowired
    private SkillService skillService;

    @RequestMapping("skillGood")
    public String skillGoods(HttpSession session, Long goodsId, Model model){
        String userId=(String) session.getAttribute("userId");
        if (userId==null){
            return "login";
        }
//        查库存  判断用户选的商品库存是否够 或者大于0  才能进行操作
        GoodsVo goodsVo=goodsService.getgoodsvobyid(goodsId);
        if (goodsVo.getStockCount()<=0){
            model.addAttribute("errmsg","库存不够了");
            return "miaosha_fail";
        }
//        查看当前用户之前是否已经秒杀过该商品了  单个商品只能每人一次
        SkillOrder skillOrder = skillOrderService.getOne(Wrappers.<SkillOrder>lambdaQuery().eq(SkillOrder::getGoodsId, goodsId).eq(SkillOrder::getUserId, userId));
        if (skillOrder!=null){
            model.addAttribute("errmsg","该商品只能秒杀一次");
            return "miaosha_fail";
        }
//        如果都没问题  可以执行  删减当前商品的库存数量 以及 生成该商品的订单
        OrderInfo info=skillService.deleteKuCunAndAddDingDan(userId,goodsVo);
        model.addAttribute("goods",goodsVo);
        model.addAttribute("orderInfo",info);
        return "order_detail";


    }




}
